package com.zbkj.crmeb.merchant.api.controller;

import com.common.PageParamRequest;
import com.constants.Constants;
import com.utils.ExcelUtil;
import com.zbkj.crmeb.chant.request.PickingProductsRequest;
import com.zbkj.crmeb.chant.response.PickingProductResponse;
import com.zbkj.crmeb.chant.service.ChannelPickingService;
import com.zbkj.crmeb.export.vo.FrontPickingProductExcelVo;
import com.zbkj.crmeb.export.vo.PickingProductExcelVo;
import com.zbkj.crmeb.merchant.admin.service.MerExcelService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.BooleanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.List;
import java.util.concurrent.atomic.AtomicInteger;


/**
 * 商品表 前端控制器
 */
@Slf4j
@Controller
@RequestMapping("api/front/mer/export/excel")
@Api(tags = "导出 -- Excel")
public class FontExcelController extends ApiBaseController {
    @Autowired
    private MerExcelService excelService;
    @Autowired
    private ChannelPickingService channelPickingService;

    AtomicInteger atom = new AtomicInteger(0);
    final int max = 10;

    @ApiOperation(value = "批采单商品导出")
    @RequestMapping(value = "/picking/product", method = RequestMethod.GET)
    public void pickingExport(@Validated PickingProductsRequest request, HttpServletResponse response, HttpServletRequest servletRequest){
        try{
            // 保护一下 最多允许10个人同时导出
            if(atom.getAndIncrement()<max){
                PageParamRequest pageParamRequest = new PageParamRequest();
                pageParamRequest.setPage(Constants.DEFAULT_PAGE);
                pageParamRequest.setLimit(Constants.EXPORT_MAX_LIMIT);
                request.setPage(Constants.DEFAULT_PAGE);
                request.setLimit(BooleanUtils.isTrue(request.getIsImg()) ? Constants.IMG_EXPORT_MAX_LIMIT : Constants.EXPORT_MAX_LIMIT);
                request.setIsApplet(1);
//                request.setMerId(getMerId(servletRequest));
                List<PickingProductResponse> responseList = channelPickingService.getProducts(request).getList();
                List<FrontPickingProductExcelVo> list  = excelService.parseFrontPickingVoList(responseList);
                //sheet名称
                ExcelUtil.setSheetName("picking");
                //文件名称前缀
                ExcelUtil.setFileName("批采单商品导出");
                ExcelUtil.writeExcelByIsImg(response, list, FrontPickingProductExcelVo.class,request.getIsImg());
            }
        }finally {
            atom.decrementAndGet();
        }
    }

}



